package com.suman.bbcticker.service;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.util.Xml;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.suman.bbcticker.FeedItem;
import com.suman.bbcticker.R;
import com.suman.bbcticker.RssFeed;

public class DisplayNewsActivity extends Activity {
	private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
	private static String NEXT_CLICK = "nextClick";
	private static String PREV_CLICK = "prevClick";
	 private static final int IO_BUFFER_SIZE = 4 * 1024;
	private static final String TAG = "DisplayNewsActivity";

	private static int currentPageDisplayIndex = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		currentPageDisplayIndex = 0;
		Intent launchIntent = getIntent();
		Bundle extras = launchIntent.getExtras();
		if (extras != null) {
			mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
		}
		setContentView(R.layout.custom_dialog_activity);
		TextView popupTextView = (TextView) findViewById(R.id.rssbbcpopup_text);
		
		
		
		RssFeed currentRssFeed = RssReaderService.currentRssFeedObject;
		List<FeedItem> feedList = currentRssFeed.getFeedList();
		final FeedItem feedItem = feedList.get(0);
		popupTextView.setText(styleString(feedItem));
		updateDateAndTimeOfFeed(feedItem);		
		new FullWebPageReaderAsyncTask().execute(feedItem.getLink());
		//new ImageDownloadAsyncTask().execute(feedItem.getMediaLink());
		

		ImageButton prevButton = (ImageButton) findViewById(R.id.rsspopup_prev);

		prevButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				updateStateOfScreenWithClick(PREV_CLICK);
			}

		});

		ImageButton closeButton = (ImageButton) findViewById(R.id.rsspopup_closebutton);

		closeButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				 finish();
			}

		});

		ImageButton nextButton = (ImageButton) findViewById(R.id.rsspopup_next);

		nextButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				updateStateOfScreenWithClick(NEXT_CLICK);

			}

		});
		
		
		ImageButton goToSite = (ImageButton)findViewById(R.id.rsspopup_gotosite);
		
		goToSite.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				goToWebViewWithUrl(feedItem.getLink());

			}
		});
		

		prevButton.setVisibility(android.view.View.INVISIBLE);
		nextButton.setVisibility(android.view.View.VISIBLE);
	}

	protected void goToWebViewWithUrl(String link) {
		Intent goToWebViewIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
		startActivity(goToWebViewIntent);
	}

	private void updateDateAndTimeOfFeed(FeedItem feedItem) {
		TextView dateAndTimeView = (TextView) findViewById(R.id.rssbbcpopup_dateandtime);
		dateAndTimeView.setText(feedItem.getPubdate());
	}

	private Spanned styleString(FeedItem feedItem) {
		return Html.fromHtml("<b>" + feedItem.getTitle() + "</b>" + "<br/>" + feedItem.getDescription());
	}

	//@+id/rssbbcpopup_dateandtime

	protected void updateStateOfScreenWithClick(String clickType) {
		RssFeed currentRssFeed = RssReaderService.currentRssFeedObject;
		TextView popupTextView = (TextView) findViewById(R.id.rssbbcpopup_text);
		ImageButton prevButton = (ImageButton) findViewById(R.id.rsspopup_prev);
		ImageButton nextButton = (ImageButton) findViewById(R.id.rsspopup_next);
		TextView popupTextViewExtended = (TextView) findViewById(R.id.rssbbcpopupextended_text);
		ProgressBar progressBar = (ProgressBar)findViewById(R.id.rssbccprogressbar);
		List<FeedItem> feedList = currentRssFeed.getFeedList();
		prevButton.setVisibility(View.VISIBLE);
		nextButton.setVisibility(View.VISIBLE);
		progressBar.setVisibility(View.VISIBLE);
		popupTextViewExtended.setVisibility(View.INVISIBLE);

		FeedItem feedItem = null;

		if (NEXT_CLICK.equalsIgnoreCase(clickType)) {
			if (currentPageDisplayIndex != feedList.size() - 1) {
				++currentPageDisplayIndex;
			}
			feedItem = feedList.get(currentPageDisplayIndex);
		} else if (PREV_CLICK.equalsIgnoreCase(clickType)) {
			if (currentPageDisplayIndex != 0) {
				--currentPageDisplayIndex;
			}
			feedItem = feedList.get(currentPageDisplayIndex);
		}

		if (currentPageDisplayIndex == 0) {
			prevButton.setVisibility(android.view.View.INVISIBLE);
		} else if (currentPageDisplayIndex == feedList.size() - 1) {
			nextButton.setVisibility(android.view.View.INVISIBLE);
		}
		
		
		if(feedItem!=null){
			new FullWebPageReaderAsyncTask().execute(feedItem.getLink());
			//new ImageDownloadAsyncTask().execute(feedItem.getMediaLink());
			popupTextView.setText(styleString(feedItem));
			ImageButton goToSite = (ImageButton)findViewById(R.id.rsspopup_gotosite);
			final FeedItem feedItemForGoToWeb = feedItem;
			
			goToSite.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					goToWebViewWithUrl(feedItemForGoToWeb.getLink());

				}
			});
			
			
			updateDateAndTimeOfFeed(feedItem);
		}

	}
	
	
	private class FullWebPageReaderAsyncTask extends AsyncTask<String, Void, String> {
		@Override
		protected void onPostExecute(String result) {
			//Make Progressbar to invisible
			ProgressBar progressBar = (ProgressBar)findViewById(R.id.rssbccprogressbar);
			progressBar.setVisibility(View.GONE);
			
			//Update textview
			TextView popupTextView = (TextView) findViewById(R.id.rssbbcpopupextended_text);
			popupTextView.setVisibility(View.VISIBLE);
			popupTextView.setText(result);
		}

		@Override
		protected String doInBackground(String... urls) {			
			String parseBodyOfNews = parseBodyOfNews(urls[0]);			
			return parseBodyOfNews;
		}

	}

	private String parseBodyOfNews(String url) {
		try {
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			factory.setNamespaceAware(true);
			factory.setValidating(false);
			XmlPullParser xpp = factory.newPullParser();
			xpp.setFeature(Xml.FEATURE_RELAXED, true);

			URLConnection conn = new URL(url).openConnection();
			conn.setConnectTimeout(R.string.rssfeed_connecttimeout);
			conn.setReadTimeout(R.string.rssfeed_readtimeout);

			boolean pTagFound = false;
			xpp.setInput(conn.getInputStream(), "utf-8");
			int eventType = xpp.getEventType();
			String result = "";
			int pTagCount = 0;
			while (eventType != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_TAG) {
					if (xpp.getName().equals("p")) {
						if ("first".equals(xpp.getAttributeValue(null, "class"))) {
							pTagFound = true;
						}
						pTagCount++;
					}
				} else if (eventType == XmlPullParser.END_TAG) {

					if (xpp.getName().equals("p")) {
						pTagCount--;

						if (pTagFound && pTagCount == 1) {

							pTagFound = false;
							break;
						}

					}

				} else if (eventType == XmlPullParser.TEXT) {
					if (pTagFound) {
						result += xpp.getText();
					}

				}
				eventType = xpp.next();
			}

			return result;
		} catch (Throwable t) {
			t.printStackTrace();
		}
		return null;

	}

	
	private class ImageDownloadAsyncTask extends AsyncTask<String, Void, Bitmap> {
		@Override
		protected void onPostExecute(Bitmap result) {
			//Make Progressbar to invisible
			ProgressBar progressBar = (ProgressBar)findViewById(R.id.rssbccprogressbar);
			progressBar.setVisibility(View.GONE);
			
			//Update ImageView To Display Image
			ImageView popupTextView = (ImageView) findViewById(R.id.rssbbcpopup);
			popupTextView.setVisibility(View.VISIBLE);
			popupTextView.setImageBitmap(result);
		}

		@Override
		protected Bitmap doInBackground(String... urls) {			
			Bitmap popupImageBitMap = loadPhotoBitmap(urls[0]);
			return popupImageBitMap;
		}

	}
	
	

	
	 private Bitmap loadPhotoBitmap(String url) {
         Bitmap bitmap = null;
         InputStream in = null;
         BufferedOutputStream out = null;

         try {
             	in = new BufferedInputStream(new URL(url).openStream(),IO_BUFFER_SIZE);
                 final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
                 out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
                 copy(in, out);
                 out.flush();

                 final byte[] data = dataStream.toByteArray();
                 bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

         } catch (IOException e) {
             android.util.Log.e(TAG, "Could not load photo: " + this, e);
         } finally {
             closeStream(in);
             closeStream(out);
         }

         return bitmap;
     }
	 
	 /**
	     * Copy the content of the input stream into the output stream, using a temporary
	     * byte array buffer whose size is defined by {@link #IO_BUFFER_SIZE}.
	     *
	     * @param in The input stream to copy from.
	     * @param out The output stream to copy to.
	     *
	     * @throws IOException If any error occurs during the copy.
	     */
	    private static void copy(InputStream in, OutputStream out) throws IOException {
	        byte[] b = new byte[IO_BUFFER_SIZE];
	        int read;
	        while ((read = in.read(b)) != -1) {
	            out.write(b, 0, read);
	        }
	    }
	    
	    /**
	     * Closes the specified stream.
	     *
	     * @param stream The stream to close.
	     */
	    private static void closeStream(Closeable stream) {
	        if (stream != null) {
	            try {
	                stream.close();
	            } catch (IOException e) {
	                android.util.Log.e(TAG, "Could not close stream", e);
	            }
	        }
	    }
	
	
	
	
	
	
	
	
	

}
